/*
 * File Name:               XProperty.cs
 *
 * Description:             简单的侦察者模式实现数据单向绑定
 *                          简化频繁的事件传递
 *                          数据双向绑定目前没感觉到意义
 * Author:                  lisiyu
 * Create Date:             2016/09/14
 */

using System;

public interface IXProperty
{ }


public class XProperty<T> : IXProperty
{
    [NickName("Value")]
    private T _Value;
    private Action<T> _OnValueChanged;

    public T Value
    {
        get
        {
            return _Value;
        }
        set
        {
            _Value = value;
        }
    }

    public XProperty()
    {

    }

    public XProperty(T value)
    {
        _Value = value;
    }

    public void setProperty(T value)
    {
        _Value = value;

        if (_OnValueChanged != null)
            _OnValueChanged(_Value);
    }

    public void setProperty(Action<T> callback)
    {
        callback(_Value);

        if (_OnValueChanged != null)
            _OnValueChanged(_Value);
    }

    public void setProperty(Func<T, T> callback)
    {
        _Value = callback(_Value);

        if (_OnValueChanged != null)
            _OnValueChanged(_Value);
    }

    public T getProperty()
    {
        return _Value;
    }

    public void addListener(Action<T> callback)
    {
        _OnValueChanged += callback;
    }

    public void removeListener(Action<T> callback)
    {
        _OnValueChanged -= callback;
    }

    public void removeListeners()
    {
        _OnValueChanged = null;
    }

    public void refresh()
    {
        if (_OnValueChanged == null)
            return;
        _OnValueChanged(_Value);
    }
}